<template>
    <div class="px-[30px] py-5 user-info">
        <div class="border-b border-br pb-5">
            <span class="text-2xl font-medium">身份认证</span>
        </div>
        <div class="mt-5">
            <div class="info-item leading-10 flex justify-between">
                <div class="item-name">社团社员</div>
                <div>
                    <span v-if="userInfo.memberCode == 'member'">已认证
                    <Icon name="el-icon-Select" />
                    </span>
                    <ElButton
                        v-else
                        link
                        type="primary"
                        @click="showMobilePopup = true"
                    >
                        未认证
                        <Icon name="el-icon-ArrowRight" />
                    </ElButton>
                </div>
            </div>
            <div class="info-item leading-10 flex justify-between">
                <div class="item-name">社团管理员</div>
                <div>
                    <span v-if="userInfo.adminCode == 'admin'">已认证
                    <Icon name="el-icon-Select" />
                    </span>
                  <ElButton
                      v-else
                      link
                      type="primary"
                      @click="showAdminPopup = true"
                  >
                    未认证
                    <Icon name="el-icon-ArrowRight" />
                  </ElButton>
                </div>
            </div>
        </div>
        <ClientOnly>
            <ElDialog
                v-model="showMobilePopup"
                :width="400"
                :close-on-click-modal="false"
            >
                <div class="px-5">
                    <div class="flex justify-between">
                        <span class="text-4xl">社团成员认证</span>
                    </div>
                    <ElForm
                        ref="formRef"
                        class="mt-[35px]"
                        size="large"
                        :model="formData"
                        :rules="formRules"
                    >
                        <ElFormItem prop="cover" label="头像">
                            <!--              <ElInput-->
                            <!--                  v-model="formData.cover"-->
                            <!--                  placeholder="请输入真是名字"-->
                            <!--                  type="password"-->
                            <!--                  show-password-->
                            <!--              />-->
                          <div class="avatar">
                            <ElAvatar :size="60" :src="formData.cover"></ElAvatar>
                            <div class="change-btn">
                              <CropperUpload
                                  @change="setUserInfo($event, UserFieldEnum.AVATAR)"
                              >
                                <span class="text-xs text-white">修改</span>
                              </CropperUpload>
                            </div>
                          </div>
<!--                          <div class="change-btn">-->
<!--                            <CropperUpload-->
<!--                                @change="setUserInfo($event, UserFieldEnum.AVATAR)"-->
<!--                            >-->
<!--                              <span class="text-xs text-white">修改</span>-->
<!--                            </CropperUpload>-->
<!--                          </div>-->
                        </ElFormItem>
                        <ElFormItem prop="name" label="名字">
                            <ElInput
                                v-model="formData.name"
                                placeholder="请输入名字"
                            />
                        </ElFormItem>
                        <ElFormItem prop="age" label="年龄">
                            <ElInput
                                v-model="formData.age"
                                placeholder="请输入年龄"
                            />
                        </ElFormItem>

                        <ElFormItem prop="sex" label="性别">
                            <el-select
                                v-model="formData.sex"
                                placeholder="请选中性别"
                            >
                              <el-option label="男" value="1"/>
                              <el-option label="女" value="0"/>
                            </el-select>

                        </ElFormItem>
                        <ElFormItem prop="contact" label="联系电话">
                            <ElInput
                                v-model="formData.contact"
                                placeholder="请输入联系电话"
                            />
                        </ElFormItem>
                        <ElFormItem prop="studentNum" label="学号">
                            <ElInput
                                v-model="formData.studentNum"
                                placeholder="请输入学号"
                            />
                        </ElFormItem>
                        <ElFormItem prop="college" label="学院">
                            <ElInput
                                v-model="formData.college"
                                placeholder="请输入学院"
                            />
                        </ElFormItem>
                        <ElFormItem prop="grade" label="年级">
                            <ElInput
                                v-model="formData.grade"
                                placeholder="请输入年级，如2022级"
                            />
                        </ElFormItem>
                        <ElFormItem prop="major" label="专业">
                          <ElInput
                              v-model="formData.major"
                              placeholder="请输入专业"
                          />
                        </ElFormItem>

                        <ElFormItem class="mt-[60px]">
                            <ElButton
                                class="w-full"
                                type="primary"
                                @click="handleConfirmLock"
                                :loading="isLock"
                            >
                                确认
                            </ElButton>
                        </ElFormItem>
                    </ElForm>
                </div>
            </ElDialog>
        </ClientOnly>


      <ClientOnly>
        <ElDialog
            v-model="showAdminPopup"
            :width="400"
            :close-on-click-modal="false"
        >
          <div class="px-5">
            <div class="flex justify-between">
              <span class="text-4xl">社团管理员认证</span>
            </div>
            <ElForm
                ref="formRef"
                class="mt-[35px]"
                size="large"
                :model="collegeData"
                :rules="formRules"
            >
              <ElFormItem prop="name" label="学院名字">
                <ElInput
                    v-model="collegeData.name"
                    placeholder="请输入学院名字"
                />
              </ElFormItem>
              <ElFormItem prop="logo" label="社团图标">
                <el-upload
                    class="avatar-uploader"
                    :auto-upload="false"
                    :action="action"
                    :show-file-list="false"
                    :on-change="(file,fileLists) => handleFileChange(file,fileLists,'logo')"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                >
                  <img v-if="collegeData.logo" :src="collegeData.logo" class="avatar" />
<!--                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>-->
                  <Icon v-else name="el-icon-Plus" />
                </el-upload>
              </ElFormItem>

              <ElFormItem prop="cover" label="学院封面">
                <el-upload
                    class="avatar-uploader"
                    :auto-upload="false"
                    :action="action"
                    :show-file-list="false"
                    :on-change="(file,fileLists) => handleFileChange(file,fileLists,'cover')"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                >
                  <img v-if="collegeData.cover" :src="collegeData.cover" class="avatar" />
<!--                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>-->
<!--                  <el-icon><Plus /></el-icon>-->
                  <Icon v-else name="el-icon-Plus" />
                </el-upload>
              </ElFormItem>
              <ElFormItem prop="attachment" label="认证资料">
                <el-upload
                    action="#"
                    :file-list="files.fileList"
                    class="upload-demo"
                    :http-request="handleFileChangeList"
                    :on-remove="handleRemove"
                >
                  <el-button type="primary">点击上传</el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      jpg/png 图片文件格式小于500kb
                    </div>
                  </template>
                </el-upload>
              </ElFormItem>

              <ElFormItem class="mt-[60px]">
                <ElButton
                    class="w-full"
                    type="primary"
                    @click="handleConfirmCollege"
                    :loading="isLoad"
                >
                  确认
                </ElButton>
              </ElFormItem>
            </ElForm>
          </div>
        </ElDialog>
      </ClientOnly>
    </div>
</template>
<script lang="ts" setup>
import {getUserInfo } from '@/api/user'
import {
    ElForm,
    ElFormItem,
    ElInput,
    ElButton,
    FormInstance,
    FormRules,
    ElDialog,
    ElUpload,
    UploadProps,
    UploadUserFile
} from 'element-plus'
import {
    useAccount
} from '~~/layouts/components/account/useAccount'
import { useUserStore } from '@/stores/user'
import CropperUpload from '@/components/cropper-upload/index.vue'
import {postMemberAdmin, postMemberAuth} from "~/api/member";
const uploadRef = shallowRef<InstanceType<typeof ElUpload>>()
const { data: userInfo, refresh } = await useAsyncData(() => getUserInfo(), {
    default: () => ({}),
    initialCache: false
})
enum UserFieldEnum {
  NONE = '',
  AVATAR = 'avatar',
  USERNAME = 'account',
  NICKNAME = 'nickname',
  SEX = 'sex'
}
const action = ref('/api/upload/image')
const userStore = useUserStore()
const showMobilePopup = ref(false)
const showAdminPopup = ref(false)
const { setPopupType, toggleShowPopup } = useAccount()
const formRef = shallowRef<FormInstance>()
const formRules: FormRules = {
    old_password: [
        {
            required: true,
            message: '请输入原密码',
            trigger: ['change', 'blur']
        }
    ],
    password: [
        {
            required: true,
            message: '请输入6-20位数字+字母或符号组合',
            trigger: ['change', 'blur']
        },
        {
            min: 6,
            max: 20,
            message: '密码长度应为6-20',
            trigger: ['change', 'blur']
        }
    ],
    contact: [
      { required: true, message: '请输入联系电话', trigger: 'blur' },
      { pattern: /^1[3456789]\d{9}$/, message: '联系电话格式不正确', trigger: 'blur' }
    ]
}
const formData = reactive({
    name: '',
    cover: '',
    age: '',
    sex: '',
    studentNum: '',
    college: '',
    grade: '',
    contact: '',
    major: ''
})

const collegeData = reactive({
  name: '',
  cover: '',
  logo: '',
  lists: ''
})
const files = reactive({
  fileList: [],
})

const setUserInfo = async (
    value: string,
    type: string
): Promise<void> => {
  formData.cover = value
  refresh()
}

const handleConfirm = async () => {
    await formRef.value?.validate()
    await postMemberAuth(formData)
    showMobilePopup.value = false
    refresh()
}

const handleConfirm2 = async () => {
  await formRef.value?.validate()
  if(files.fileList&&files.fileList.length>0){
    collegeData.lists = files.fileList
  }
  await postMemberAdmin(collegeData)
  showMobilePopup.value = false
  refresh()
}
const { lockFn: handleConfirmLock, isLock } = useLockFn(handleConfirm)


const fileList = ref([])
// const handleChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
//   fileList.value = fileList.value.slice(-3)
// }
const { lockFn: handleConfirmCollege, isLoad } = useLockFn(handleConfirm2)

const handleFileChange = async (file:any, fileList:any,key:string) => {
  const imgFile = new window.File([file.raw], file.raw.name, {
    type: file.raw.type
  })
  const data = await uploadImage({ file: imgFile })
  collegeData[key] = data.uri
}

const handleFileChangeList = async (file:any, uploadFiles:any,key:string) => {
  const imgFile = new window.File([file.file], file.file.name, {
    type: file.file.type
  })
  const data = await uploadImage({ file: imgFile })
  files.fileList.push({
    name: data.name, // 文件名
    url: data.uri, // 服务器返回的文件 URL
    status: 'success', // 标记为上传成功
  });
  console.log(files.fileList)
}

// 处理文件移除
const handleRemove = (file, fileList) => {
  files.fileList = fileList; // 更新 fileList
}

import { UploadProps } from 'element-plus'
import {uploadImage} from "~/api/app";

const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log(rawFile)
  if (!rawFile.type.includes('image/')) {
    ElMessage.error('只能上传图片格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传文件小于2MB!')
    return false
  }
  return true
}

definePageMeta({
    module: 'personal',
    auth: true
})
</script>
<style lang="scss" scoped>
.user-info {
    .info-item {
        display: flex;
        align-items: center;
        border-bottom: 1px solid var(--el-border-color);
        padding: 10px 0;
        .item-name {
            width: 80px;
            color: var(--el-text-color-regular);
        }
    }
    .avatar {
      @apply relative flex cursor-pointer;
      .change-btn {
        display: none;
        height: 50%;
        line-height: 30px;
        @apply absolute bg-[rgba(0,0,0,0.5)]  w-full text-center bottom-0 rounded-b-full;
      }
      &:hover {
        .change-btn {
          display: block;
        }
      }
    }
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
 .avatar-uploader .el-upload {
   border: 1px dashed var(--el-border-color);
   border-radius: 6px;
   cursor: pointer;
   position: relative;
   overflow: hidden;
   transition: var(--el-transition-duration-fast);
 }

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon[name='el-icon-Plus'] {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
